package com.globaldom.web.stats;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.Stats;
import com.globaldom.utils.EMF;
import com.globaldom.utils.MemCacheManager;
/* Change this class to store maps (CountryCode, Stat) directly to memcache with 24 hours expiry.
 * Update the map every 24 hours(as requested thru this page)
 *
 *
 */
@Controller
@RequestMapping(value = "/stats")
public class StatsController {
	public StatsController() {
	}
	private static final Logger log = Logger.getLogger(StatsController.class.getName());
	// initializing method
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model, HttpSession session) {

		Map<String, Long> countryMap = new HashMap<String, Long>();


		EntityManager em = EMF.get().createEntityManager();
		List<Stats> stats = em.createQuery("Select s from Stats s").getResultList();
		for (Iterator<Stats> iterator = stats.iterator(); iterator.hasNext();) {
			Stats _stats = (Stats) iterator.next();
			
			countryMap.put(_stats.getCountryParam(), _stats.getStatValue());
			
		}
		Map<Long, Long> personalStats = MemCacheManager.getAllPersonalStats();
//		countryMap.put("NO", 7l);
//		countryMap.put("NG", 3l);
//		countryMap.put("CH", 37l);
//		countryMap.put("LK", 47l);

		model.addAttribute("countrystats", countryMap);
		model.addAttribute("personalstats", personalStats);
		return "stats";
	}

	@RequestMapping(value = "/updatelocations", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> updateLocations(HttpSession session, long personid, String countryid) {

		EntityManager em = EMF.get().createEntityManager();
		try {
			Stats stat = null;
			//stat = MemCacheManager.getCountryStats(countryid);
			//if (null == stat) {
				String sql = "Select s from Stats s where statType=0 and countryParam=:country";
				Query q = em.createQuery(sql);
				q.setParameter("country", countryid);

				try {
					stat = (Stats) q.getSingleResult();
				} catch (Exception ede) {
					log.severe(ede.toString());
				}
				if (null == stat) {
					stat = new Stats();
					stat.setStatType(0);
					stat.setCountryParam(countryid);
					stat.setStatValue(1l);
				}

			//}
			stat.setStatValue(stat.getStatValue() + 1);
			em.persist(stat);
			//MemCacheManager.putCountryStats(countryid, stat);
		} catch (Exception ex) {
			log.severe("Exception while excepting..." + ex.getMessage());
		} finally {
			em.close();
		}

		return null;
	}

}
